package com.motu.monstercity.server.game.logic;

import com.motu.monstercity.module.common.utility.CmdConstant;
import com.motu.monstercity.module.common.utility.EventBusConstant;
import com.motu.monstercity.protocol.Common.PBFunctionClient;
import com.motu.monstercity.protocol.Common.PBSystemOpen;
import com.motu.monstercity.protocol.Common.PBUserData;
import com.motu.monstercity.server.game.base.ProtoDataUtils;
import com.motu.monstercity.server.game.commondata.act.ActWord;
import com.motu.monstercity.server.game.commondata.bag.ItemId;
import com.motu.monstercity.server.game.commondata.maintask.MainTaskConstant;
import com.motu.monstercity.server.game.commondata.system.DecorateMain;
import com.motu.monstercity.server.game.commondata.system.SystemConstant;
import com.motu.monstercity.server.game.commondata.system.SystemOpen;
import com.motu.monstercity.server.game.commondata.system.SystemWord;
import com.motu.monstercity.server.game.log.LogType;
import com.motu.monstercity.server.game.log.MotuLogManager;
import com.motu.monstercity.server.game.userdata.*;
import com.motu.vertx.module.utility.base.ServerTypeEnum;
import com.motu.vertx.module.utility.main.MainService;
import com.motu.vertx.module.utility.model.EntityManager;
import com.motu.vertx.module.utility.model.Model;
import com.motu.vertx.module.utility.toolset.TimeUtils;
import com.motu.vertx.module.utility.toolset.Tool;
import io.vertx.core.eventbus.EventBus;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.auth.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

public class GameDataManager extends GameBaseData {
    public final static Logger logger = LoggerFactory.getLogger(GameDataManager.class);

    public static final int DECORATE_TYPE_1 = 1;// 1为头像，配置id为601001~601999
    public static final int DECORATE_TYPE_2 = 2;// 2为头像框，配置id为602001~602999
    public static final int DECORATE_TYPE_3 = 3;// 3为称号，
    public static final int DECORATE_TYPE_4 = 4;// 4为聊天气泡，

    /**
     * 判断是否有包含本服
     */
    public static boolean isServerRange(int serverid, byte rtype, String rang) {
        boolean contain = false;// 是否包含
        if (rtype == 0) {// 全部
            contain = true;
        } else if (rtype == 1) {// 包含
            JsonArray jsonArray = new JsonArray(rang);
            if (jsonArray.contains(serverid)) {
                contain = true;
            }
        } else if (rtype == 2) {// 不包含
            JsonArray jsonArray = new JsonArray(rang);
            if (!jsonArray.contains(serverid)) {
                contain = true;
            }
        }
        return contain;
    }

    /**
     * 判断是否有包含渠道
     */
    private static boolean isPlatformRange(String platforms, int platform) {
        if (Tool.isEmpty(platforms)){
            return true;
        }
        String[] array = platforms.split(",");
        for (String val : array) {
            if (platform == Integer.parseInt(val)){
                return true;
            }
        }
        return false;
    }

    public static List<PBFunctionClient> getFunctionClientList(int serverId, int platform){
        List<PBFunctionClient> list = new ArrayList<>();
        for (JsonObject jsonObject : getFunctionClientMap().values()){
            if (!isServerRange(serverId, jsonObject.getInteger("rtype").byteValue(), jsonObject.getString("rang"))) {
                continue;
            }
            if (!isPlatformRange(jsonObject.getString("platform"), platform)) {
                continue;
            }
            PBFunctionClient.Builder functionClient = PBFunctionClient.newBuilder();
            functionClient.setId(jsonObject.getInteger("id"));
            functionClient.setOpen(jsonObject.getInteger("open") == 1);
            list.add(functionClient.build());
        }
        return list;
    }




    // 获取系统文字
    public static String getSystemWordByLanguage(int id, int language) {
        ConcurrentHashMap<Integer, SystemWord> systemWordMap = getSystemWordMap();
        if (systemWordMap.containsKey(id)) {
            return systemWordMap.get(id).getWord(language);
        } else {
            return null;
        }
    }

    // 根据语言获取对应的系统文字
    public static String getSystemWord(int id, int language, Object... params) {
        String word = getSystemWordByLanguage(id, language);
        if (word == null || word.isEmpty()) {
            return String.valueOf(id);
        }
        if (params.length == 0) {
            return word;
        }
        String content = "";
        try {
            content = String.format(word, params);
        } catch (Exception e) {
            content = String.valueOf(id);
        }
        return content;
    }

    public static int getSystemWordMailType(int wordId) {
        ConcurrentHashMap<Integer, SystemWord> systemWordMap = getSystemWordMap();
        if (systemWordMap.containsKey(wordId)) {
            return systemWordMap.get(wordId).getType();
        } else {
            //logger.error("getSyswords error key:"+key);
            return 0;
        }
    }

    public static boolean isSystemWord(int wordId) {
        ConcurrentHashMap<Integer, SystemWord> systemWordMap = getSystemWordMap();
        return systemWordMap.containsKey(wordId);
    }

    // 根据语言获取对应的系统文字act_word
    public static String getActWord(int id, int language, Object... params) {
        String word = getActWordByLanguage(id, language);
        if (word == null || word.isEmpty()) {
            return String.valueOf(id);
        }
        if (params.length == 0) {
            return word;
        }
        String content = "";
        try {
            content = String.format(word, params);
        } catch (Exception e) {
            content = String.valueOf(id);
        }
        return content;
    }

    public static int getActWordMailType(int wordId) {
        ConcurrentHashMap<Integer, ActWord> actWordMap = getActWordMap();
        if (actWordMap.containsKey(wordId)) {
            return actWordMap.get(wordId).getType();
        } else {
            //logger.error("getActWord error key:"+key);
            return 0;
        }
    }

    // 获取系统文字从act_word
    public static String getActWordByLanguage(int id, int language) {
        ConcurrentHashMap<Integer, ActWord> actWordMap = getActWordMap();
        if (actWordMap.containsKey(id)) {
            return actWordMap.get(id).getWord(language);
        } else {
            return null;
        }
    }

    public static UserDecorate getUserDecorate(long userId, int decorateId) {
        return (UserDecorate) EntityManager.getEntity(UserDecorate.class, userId, decorateId);
    }

    public static List<UserDecorate> getUserDecorateList(long userId) {
        List<UserDecorate> list = new ArrayList<>();
        for (Model model : EntityManager.getEntityList(UserDecorate.class, userId)) {
            UserDecorate entity = (UserDecorate) model;
            list.add(entity);
        }
        return list;
    }

    public static UserTitle getUserTitle(long userId, int decorateId) {
        return (UserTitle) EntityManager.getEntity(UserTitle.class, userId, decorateId);
    }

    public static List<UserTitle> getUserTitleList(long userId) {
        List<UserTitle> list = new ArrayList<>();
        for (Model model : EntityManager.getEntityList(UserTitle.class, userId)) {
            UserTitle entity = (UserTitle) model;
            if (entity.isExpired(TimeUtils.getCurTime())) {
                entity.delete();// 删除已过期的称号数据
            } else {
                list.add(entity);
            }
        }
        return list;
    }


    // 获取数值类的奖励 头像,头像框,称号,聊天气泡等装饰类
    public static void addRewardDecorate(UserInfo userInfo, int itemId, int itemNum, PBUserData.Builder pbUserData, Object... logParams) {
        long userId = userInfo.getId();
        DecorateMain decorateMain = getDecorateMain(itemId);
        if (decorateMain == null) {
            return;
        }
        UserDecorate userDecorate = getUserDecorate(userId, itemId);
        if (userDecorate == null) {
            userDecorate = new UserDecorate();
            userDecorate.putUserId(userId);
            userDecorate.putDecorateId(itemId);
            userDecorate.putNum(itemNum);
            userDecorate.doCreate();
            MotuLogManager.logItemIncome(userInfo, itemId, 0, 0, 1, logParams);// 记录获得日志
            if (pbUserData != null) {
                ProtoDataUtils.updatePBUserData(pbUserData, userDecorate, true);
            }
        } else {
            if (decorateMain.getType() == SystemConstant.DECORATE_TYPE_3) {// 只有称号才可以重复获得
                userDecorate.addNum(userInfo, itemNum, logParams);
                userDecorate.update();
                if (pbUserData != null) {
                    // 像userDecorate这种叠加道具，如果通知客户端删除之后再连续获得，那么第二次update对象会覆盖第一次的完整对象，导致客户端收不到完整对象，所以直接下发完整对象
                    ProtoDataUtils.updatePBUserData(pbUserData, userDecorate, true);
                }
            }
        }
    }

    // 获得干员或是秘书时 自动解锁头像框
    public static void unlockDecorateMain(PBUserData.Builder pbUserData, UserInfo userInfo, int itemId) {
        DecorateMain decorateMain = null;
        for (DecorateMain entity : getDecorateMainMap().values()) {
            if (entity.getIconId() == itemId && entity.isUnlockAuto()) {
                decorateMain = entity;
            }
        }
        if (decorateMain == null) {
            return;
        }

        RewardManager.addReward(userInfo, decorateMain.getId(), 1, pbUserData, LogType.SYSTEM_REWARD);
    }

    public static List<PBSystemOpen> getPBSystemOpenList() {
        List<PBSystemOpen> pbSystemOpenList = new ArrayList<>();
        for (SystemOpen systemOpen : getSystemOpenList().values()) {
            pbSystemOpenList.add(systemOpen.takeBuilder());
        }
        return pbSystemOpenList;
    }


    /**
     * 通知游戏相关进程act_word更新多个id数据
     */
    public static void pushGameUpdateActWordByIds(int... ids) {
        if (ids.length == 0) {
            return;
        }
        JsonArray params = new JsonArray();
        for (int id : ids) {
            params.add(id);
        }
        JsonObject data = new JsonObject()
                .put("servertype", new JsonArray()
                        .add(ServerTypeEnum.GAME.value)
                        .add(ServerTypeEnum.TIMED_TASK.value)
                        .add(ServerTypeEnum.WEB.value))
                .put("method", "GameDataManager.updateActWordByIds")
                .put("path", "com.motu.monstercity.server.game.logic.")
                .put("params", new JsonArray().add(int[].class.getName()).add(params));
        JsonObject message = new JsonObject()
                .put("cmd", CmdConstant.GM_CMD_RELOAD_WITH_PARAMS)
                .put("data", data);
        String ebName = EventBusConstant.getAddress(EventBusConstant.GAME_GM);
        EventBus eventBus = MainService.getVertx().eventBus();
        eventBus.publish(ebName, message);//广播所有的进程重载数据
    }



    public static boolean isSystemWordType(int key) {
        return getSystemWordMap().containsKey(key);
    }
}
